import axios from "axios";
import * as consts from "@/utils/constant.js";
import { getQueryString, reauthorize } from "@/utils/index.js";

export const Sevent = axios.create({
  baseURL: consts.API_BASE_URL,
  timeout: 1000 * 60 * 3,
  withCredentials: true,
});

/** 自定义适配器，就可以实现uniapp的app和小程序开发中能使用axios进行跨域网络请求，并支持携带cookie */
Sevent.defaults.adapter = function (config) {
  return new Promise((resolve, reject) => {
    // console.log(config)
    let settle = require("axios/lib/core/settle");
    let buildURL = require("axios/lib/helpers/buildURL");
    uni.request({
      method: config.method.toUpperCase(),
      url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
      header: config.headers,
      data: config.data,
      dataType: config.dataType,
      responseType: config.responseType,
      sslVerify: config.sslVerify,
      complete: function complete(response) {
        response = {
          data: response.data,
          status: response.statusCode,
          errMsg: response.errMsg,
          header: response.header,
          config: config,
        };

        settle(resolve, reject, response);
      },
    });
  });
};

Sevent.interceptors.request.use(
  (config) => {
    if (
      config.url.indexOf("withoutLogin") == -1 ||
      config.url.indexOf("bindAndLogin") == -1 ||
      config.url.indexOf("listDept") == -1 ||
      config.url.indexOf("getAppId") == -1
    ) {
      let token = uni.getStorageSync("token");
      token && token !== "" && (config.headers.Authorization = "Bearer " + token);
    }
    if(config.url.indexOf("getAppId") != -1 || config.url.indexOf("learning") != -1){
        uni.setStorageSync("token","");
        config.headers.Authorization = "";
    }
    if(config.isToken == 0 ){
      uni.setStorageSync("token","");
      config.headers.Authorization = "";
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

Sevent.interceptors.response.use(
  (response) => {
    const res = response.data;
    console.log('res===========>>>>>',res)
     const deptId = getQueryString("deptId");
    let redirect_url = encodeURIComponent('http://testcrm.xinlanrenli.com/wechat/#/pages/HomePage/webIndex');
    if (!res) return;
    if ( res.code && res.code != 200) {
      if (res.code == 401 && process.env.VUE_APP_ENV == 'prod') {
        // token失效，重新授权
        uni.setStorageSync("token", "");
        uni.setStorageSync("token2", "");
        let openId = uni.getStorageSync("openId")
        let isAdmin = uni.getStorageSync("isAdmin")
        console.log('openId,!isAdmin',openId,!isAdmin)
        if (openId  && !isAdmin) {
          window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe0ee816af068f3a4&redirect_uri=${redirect_url}&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1&#wechat_redirect`
          uni.setStorageSync("openId", "");
          uni.setStorageSync("isAdmin", "");
        } else if (openId && isAdmin) {
          window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe0ee816af068f3a4&redirect_uri=${redirect_url}&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1&#wechat_redirect`
          uni.setStorageSync("openId", "");
          uni.setStorageSync("isAdmin", "");
        } else {
          uni.setStorageSync("resresresres", res);
          reauthorize()
        }
        // let appId = uni.getStorageSync("appId");
        // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
        //     appId
        // }&redirect_uri=${encodeURIComponent(location.href)}&response_type=code&scope=${
        //   consts.SCOPE
        // }&state=STATE&connect_redirect=1&#wechat_redirect`;
        // 增强授权功能,重新获取授权时redirectUrl携带当前RequestParams
        return;
      } else if (res.code == 410  && process.env.VUE_APP_ENV == 'prod') {
        uni.setStorageSync("ressssssss", response);
        uni.setStorageSync("token", "");
        uni.setStorageSync("token2", "");

        let openId = uni.getStorageSync("openId")
        let isAdmin = uni.getStorageSync("isAdmin")
        uni.setStorageSync("openId && !isAdmin", openId && !isAdmin);
        uni.setStorageSync("openId && isAdmin", openId && isAdmin);
        if (openId && !isAdmin) {
          // https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe0ee816af068f3a4&redirect_uri=http%3A%2F%2Ftestcrm.xinlanrenli.com%2Fwechat%2F%23%2Fpages%2FHomePage%2FwebIndex&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1&#wechat_redirect
          window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe0ee816af068f3a4&redirect_uri=${redirect_url}&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1&#wechat_redirect`
          uni.setStorageSync("openId", "");
          uni.setStorageSync("isAdmin", "");
        } else if (openId && isAdmin) {
          window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe0ee816af068f3a4&redirect_uri=${redirect_url}&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1&#wechat_redirect`
          uni.setStorageSync("openId", "");
          uni.setStorageSync("isAdmin", "");
        } else {
          uni.setStorageSync("ressssssss2", 'window.location.href');
          window.location.href = window.location.origin + window.location.pathname + '?deptId='+ deptId;
        }
        // 重新授权获取code
        return;
      }
      uni.showToast({
        title: res.msg || "数据错误请联系客服",
        icon: "error",
      });
      return Promise.reject(new Error(res.msg || "Error"));
    }
    return response;
  },
  function (error) {
    uni.showToast({
      title: error || toString(error) || "数据错误请联系客服",
      icon: "error",
    });
    return Promise.reject(error);
  }
);

/**
 * @description: 请求方法封装
 * @param {String} url 【请求的url地址，默认空字符串】
 * @param {Object} params 【请求时携带的参数，默认空对象】
 * @param {String} type 【请求方法，默认post请求】
 * @return: 【Promise对象】
 */
export function $axios(url = "", params = {}, type = "GET", isSearchParams) {
  let promise;
  return new Promise((resolve, reject) => {
    if (type.toUpperCase() === "GET"  && isSearchParams != true) {
      for (var key in params) {
        if (params.hasOwnProperty(key)) {
          var v = params[key];
          if (v !== "") {
            url += "/" + params[key];
          }
        }
      }
      promise = Sevent.get(url, { params: {} });
    } else if (type.toUpperCase() === "GET" && isSearchParams == true) {
      //
      // const queryString = new URLSearchParams(params).toString();
      // url = url
      promise = Sevent.get(url, { params: params });
    } else if (type.toUpperCase() === "POST") {
      promise = Sevent.post(url, params);
    } else if (type.toUpperCase() === "PUT") {
      if (url.indexOf("updateOtherStatus") != -1) {
        for (var key in params) {
          if (params.hasOwnProperty(key)) {
            var v = params[key];
            if (v !== "") {
              url += "/" + params[key];
            }
          }
        }
      }
      promise = Sevent.put(url, params);
    } else if (type.toUpperCase() === "DELETE") {
      promise = Sevent.delete(url, params)
    }
    promise
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
